﻿using System;
using ECommerce.Controls;
using Service;
using Data.Entity;
using System.Web.Security;

namespace ECommerce.Customer.Controls
{
	public partial class BasicInfoManage : BaseUserControl
	{
		private IUserExtensionService _UserExtensionService;

		protected void Page_Load(object sender, EventArgs e)
		{
			if(SiteContext.Current == null)
			{
				Server.Transfer("~/Login.aspx");
			}

			if(!IsPostBack)
			{
				this.ButtonSaveBasicInfo.Text = GetLocalResourceString("ECommerce.SaveButtonText");

				BindCurrentUserInfo();
			}
		}

		protected void ButtonSaveBasicInfo_Click(object sender, EventArgs e)
		{
			SaveUserInfo();

			BindCurrentUserInfo();
		}

		private void SaveUserInfo()
		{
			var currentUser = SiteContext.Current.User;
			var currentUserExt = SiteContext.Current.UserExt;

			if(currentUser != null && SiteContext.Current.WorkingLanguage != null)
			{
				currentUser.Email = TextEmail.Text;
				Membership.UpdateUser(currentUser);

				if(_UserExtensionService == null)
				{
					_UserExtensionService = new UserExtensionService();
				}

				if(currentUserExt == null)
				{
					currentUserExt = new UserExtension();

					currentUserExt.FirstName = TextFirstName.Text;
					currentUserExt.LastName = TextLastName.Text;
					currentUserExt.PhoneNumber = TextPhoneNumber.Text;
					currentUserExt.MobileNumber = TextMobileNumber.Text;
					currentUserExt.Active = true;
					currentUserExt.CurrencyID = 0;
					currentUserExt.AffiliateID = 0;
					currentUserExt.BillingAddressID = 0;
					currentUserExt.Deleted = false;
					currentUserExt.LanguageID = SiteContext.Current.WorkingLanguage.LanguageId;
					currentUserExt.LastAppliedCouponCode = string.Empty;
					currentUserExt.LastPaymentMethodID = 0;
					currentUserExt.RegistrationDate = DateTime.Now;
					currentUserExt.ShippingAddressID = 0;
					currentUserExt.Signature = string.Empty;
					currentUserExt.TotalForumPosts = 0;
					currentUserExt.UserID = new Guid(currentUser.ProviderUserKey.ToString());

					_UserExtensionService.CreateNewUserExtension(currentUserExt);
				}
				else
				{
					currentUserExt.FirstName = TextFirstName.Text;
					currentUserExt.LastName = TextLastName.Text;
					currentUserExt.PhoneNumber = TextPhoneNumber.Text;
					currentUserExt.MobileNumber = TextMobileNumber.Text;

					_UserExtensionService.UpdateUserExtension(currentUserExt);
				}
			}
		}

		private void BindCurrentUserInfo()
		{
			var currentUser = SiteContext.Current.User;
			var currentUserExt = SiteContext.Current.UserExt;

			if(currentUser != null && currentUserExt != null)
			{
				this.TextEmail.Text = currentUser.Email;
				this.TextFirstName.Text = currentUserExt.FirstName;
				this.TextLastName.Text = currentUserExt.LastName;
				this.TextPhoneNumber.Text = currentUserExt.PhoneNumber;
				this.TextMobileNumber.Text = currentUserExt.MobileNumber;
			}
		}
	}
}